import React, { Component } from 'react'
import { Link } from 'react-router-dom';
import qs from 'querystringify';
import request from '../../utils/fetch';
import NewsTabs from './NewsTabs'

export default class NewsDetail extends Component {
  constructor(props) {
    super(props)
    this.state = {
      classify: [],
      cid: 0,
      article: {
        id: props.match.params.id,
        title: '',
        source: '',
        create_time: '',
        hits: ''
      }
    }
  }
  componentDidMount() {
    this.getMain()
  }
  componentWillReceiveProps(nextProps) {
    this.setState({
      article: {
        id: nextProps.match.params.id,
        title: '',
        source: '',
        create_time: '',
        hits: ''
      }
    }, this.getMain.bind(this))
  }
  getQuery(search) {
    return qs.parse(search)
  }
  getMain() {
    Promise.all([this.getClassify(), this.getDetail()]).then(([res1, res2]) => {
      this.setState({
        cid: res2.data.classify_id,
        classify: res1.data,
        article: res2.data
      })
    }).catch(err => {
      console.log(err)
    })
  }
  getClassify() {
    return request.get(`/web/classify/getClassifyByPid?pid=1`).catch(err => {
      console.log(err)
    })
  }
  getDetail() {
    return request.get(`/web/Article/getArticleById?id=${this.state.article.id}`).catch(err => {
      console.log(err)
    })
  }
  render() {
    const pathname = this.props.location.pathname,
    search = this.getQuery(this.props.location.search),
    article = this.state.article,
    prev = article.previous_id ? pathname.replace(this.state.article.id, article.previous_id) : null,
    next = article.next_id ? pathname.replace(this.state.article.id, article.next_id) : null
    return (
      <div className="container">
        <NewsTabs search={search} classify={this.state.classify} cid={this.state.cid}></NewsTabs>
        <div className="section-news-detail p-b-4">
          <h4 className="mt-5 pb-3 text-center">{article.title}</h4>
          <div className="row mt-4 pb-3" style={{color: '#aaa'}}>
            <div className="offset-lg-2 col-lg-3">作者：{article.source}</div>
            <div className="col-lg-4">发表时间：{article.create_time}</div>
            <div className="col-lg-2">浏览数：{article.hits + article.hits_base}</div>
          </div>
          <div className="mt-4 pb-4" dangerouslySetInnerHTML={{__html: article.content }}></div>
        </div>
        <div className="row justify-content-between mt-4">
        {
          prev ? 
          <Link to={prev}>
            <button type="button" className="btn btn-primary">上一篇</button>
          </Link> : <span></span>
        }
        {
          next ? 
          <Link to={next}>
            <button type="button" className="btn btn-primary">下一篇</button>
          </Link> : <span></span>
        }
        </div>
      </div>
    )
  }
}
